package com.system.data.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;


public class ConfigurationReader {
	
	private static Map<String, String> properties = new HashMap<String, String>();
	
	public static String getPropery(final String key){
		String result = null;
		if (key != null) {
			if(properties.isEmpty()){
				getProperties();
			}
			result = properties.get(key);
		}
		return result;
	}
	
	/**
	 * Load *.properties in ${jboss_home}/configPortfolio folder into variable properties
	 * @param fileName
	 * @return HashMap contains content of file
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	private static Map<String, String> loadPropertiesFile(final String fileName) throws URISyntaxException, IOException {
		final File configFile = new File(Constants.PROPERTY_PATH_LOCAL + fileName);
		if (configFile.exists()) {
			final Properties props = new Properties();
			final HashMap<String, String> mapProperties = new HashMap<String, String>();
			final InputStream inputStream = Thread.currentThread().
					getContextClassLoader().getResourceAsStream(Constants.PROPERTY_PATH_LOCAL + fileName);
	        props.load(inputStream);
			String key = "";
			final Iterator<Object> iterator = props.keySet().iterator();
			while(iterator.hasNext()) {
				key  = (String)iterator.next();
				mapProperties.put(key, (String)props.get(key));
			}
			return mapProperties;
		} else {
			return null;
		}
	}
	
	/**
	 * 
	 * @return map of name / value pairs for portfolio related configuration 
	 * @throws URISyntaxException When portfolio property location is invalid
	 * @throws IOException When portfolio property file could not be read
	 * @see Constants#PORTFOLIO_PROPERTY_FILE
	 */
	private static Map<String, String> getProperties(){
		synchronized (properties) {
			if (properties.isEmpty()){
				try{
					properties = loadPropertiesFile(Constants.PROPERTY_FILE);
				} catch (Exception e) {
					//TODO Logging
				}
			}
		}
		return properties;
	}
}
